package ThreadDemo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-10-10
 * Time: 18:03
 */
//懒汉模式
class SingletonLazy {
    //加 volatile 为了避免编译器优化，不取内存中的数据，和指令重排序问题
    volatile public static SingletonLazy singletonLazy = null;

    //调用这个函数时，才去创建对象返回
    public static SingletonLazy GetInstance() {
        if (singletonLazy == null) { //避免第一次创建对象后，每一次都进行判断
            synchronized (SingletonLazy.class) {//避免多线程下的操作
                if (singletonLazy == null) {
                    singletonLazy = new SingletonLazy();
                    return singletonLazy;
                }
            }
        }
        return singletonLazy;
    }

    private SingletonLazy() {

    }
}

public class ThreadDemo19 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.GetInstance();
        SingletonLazy s2 = SingletonLazy.GetInstance();

        System.out.println(s1 == s2 ? 1 : 2);
    }
}
